<?php !defined('IN_RUN') && exit('Access Denied');
/*********************************************
* @Name:   GAY - Framework v1.0
* @Type:   Function core
* @Author: Adolf
* @Email:  qingbin.zhang@baifendian.com
*********************************************/

/*字符串->带引号字符  'a,b,cd' => 'a','b','cd'*/
function stringTochar($a){
	$val="'";	
	if(is_array($a)) $a = implode(',',$a);
	for($i = 0 ; $i < strlen($a); $i++) {
		$a{$i} != "," ? $val .= $a{$i} : $val .= "'".$a{$i}."'";
		if($i+1 == strlen($a)) $val .= "'";	
	}
	return $val;
}

//对象转数组
function objectToArray($d) {
	if (is_object($d)) {
		$d = get_object_vars($d); 
	}
	if (is_array($d)) {
		return array_map(__FUNCTION__, $d);
	}
	else {
		return $d;
	}
}
//数组转对象
function arrayToObject($d) {
	if (is_array($d)) {
		return (object) array_map(__FUNCTION__, $d);
	}
	else {
		return $d;
	}
}
/**
 * name:二维数组排序
 */
function array_sort($arr,$keys,$type='asc'){ 
	$keysvalue = $new_array = array();
	foreach ($arr as $k=>$v){
		$keysvalue[$k] = $v[$keys];
	}
	if($type == 'asc'){
		asort($keysvalue);
	}else{
		arsort($keysvalue);
	}
	reset($keysvalue);
	foreach ($keysvalue as $k=>$v){
		$new_array[$k] = $arr[$k];
	}
	return $new_array; 
} 
/**
 * name:读取有格式的文件(txt等)
 * value:返回数组
 */
function openFile($path){
	if (!file_exists($path)) {
		echo "unexists:$path";
		exit();
	}
	$result = array();
	//读取txt内容列表
	$file = fopen($path,"r");
	while(! feof($file)){
		$linestr = fgets($file);
		$linestr = preg_replace("/[\n\r]/i","",$linestr);
		//先对行做trim
		$linestr = trim($linestr);
		if($linestr==="")
		continue;	
		//支持"#"开头的行注释
		if($linestr[0] === "#"){
			continue;
		}
		//支持锁紧或者空格分隔
		$values = preg_split("/[\s\t]+/", $linestr); 
		$result[] = $values;
	}
	fclose($file);
	return $result;
}

/**
 * 删选数据工具
 * 正则：删选文字中含有其它内容的值
 * name:删选指定文件数据，移植删选数据生成到指定文件
 * param：1.删选文件2.生成文件
 */
function array2txt($old_txt='',$new_txt=''){
	$arr = openFile($old_txt);
	foreach($arr as $k=>$v){
		if(@eregi("[^\x80-\xff]",$v[2])){	
			$val[] = $arr[$k];
		}else{
			$val2[] = $arr[$k];	
		}
	}	
	//unix和linux下面是\n，windows下面是\r\n
	$str_new = '';
	foreach($val as $k2=>$v2){
		$str_new.=$v2[0]."\t".$v2[1]."\t".$v2[2]."\r\n";        
	}
	$kv=fopen($new_txt,"w+");
	fwrite($kv,$str_new);
	fclose($kv);	
	
	unlink($old_txt);
	$str_old = '';
	foreach($val2 as $k3=>$v3){
		@$str_old.=$v3[0]."\t".$v3[1]."\t".$v3[2]."\r\n";        
	}
	$kv2=fopen($old_txt,"w+");
	fwrite($kv2,$str_old);
	fclose($kv2);		
}

//文件是否存在，包括本地和远程文件 
function my_file_exists($file)
{
	if(preg_match('/^http:\/\//',$file)){
		//远程文件
		if(ini_get('allow_url_fopen')){
			if(@fopen($file,'r')) return true;
		}
		else{
			$parseurl=parse_url($file);
			$host=$parseurl['host'];
			$path=$parseurl['path'];
			$fp=fsockopen($host,80, $errno, $errstr, 10);
			if(!$fp)return false;
			fputs($fp,"GET {$path} HTTP/1.1 \r\nhost:{$host}\r\n\r\n");
			if(preg_match('/HTTP\/1.1 200/',fgets($fp,1024))) return true;
		}
		return false;
	}
	return file_exists($file);
}

//------------------------------------------------------------------------------------------------------
/**
 * 对用户的密码进行加密
 * @param $password
 * @param $encrypt //传入加密串，在修改密码时做认证
 * @return array/password
 */
function md5_password($password, $encrypt='') {
	$pwd = array();
	$pwd['encrypt'] =  $encrypt ? $encrypt : random(6);
	$pwd['password'] = md5(md5(trim($password)).$pwd['encrypt']);
	return $encrypt ? $pwd['password'] : $pwd;
}

/**
* 生成随机数(1数字,0字母数字组合)
*
* @param int $length 随机数长度
* @param int $length 随机数长度
*/
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
	$seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed[mt_rand(0, $max)];
	}
	return $hash;
}
//------------------------------------------------------------------------------------------------------

 /**
 * 检测输入中是否含有错误字符
 *
 * @param char $string 要检查的字符串名称
 * @return TRUE or FALSE
 */
function is_badword($string) {
	$badwords = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n","#");
	foreach($badwords as $value){
		if(strpos($string, $value) !== FALSE) {
			return TRUE;
		}
	}
	return FALSE;
}

/**
 * 检查id是否存在于数组中
 *
 * @param $id
 * @param $ids
 * @param $s
 */
function check_in_array($id, $ids = '', $s = ',') {
	if(!$ids) return false;
	$ids = explode($s, $ids);
	return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
}

/**
 * 对数据进行编码转换
 * @param array/string $data       数组
 * @param string $input     需要转换的编码
 * @param string $output    转换后的编码
 */
function array_iconv($data, $input = 'gbk', $output = 'utf-8') {
	if (!is_array($data)) {
		return iconv($input, $output, $data);
	} else {
		foreach ($data as $key=>$val) {
			if(is_array($val)) {
				$data[$key] = array_iconv($val, $input, $output);
			} else {
				$data[$key] = iconv($input, $output, $val);
			}
		}
		return $data;
	}
}

/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function str_cut($string, $length, $dot = '...') {
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	if(strtolower(CHARSET) == 'utf-8') {
		$length = intval($length-strlen($dot)-$length/3);
		$n = $tn = $noc = 0;
		while($n < strlen($string)) {
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t <= 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) {
				break;
			}
		}
		if($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
		$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
	} else {
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen - 1;
		$current_str = '';
		$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
		$replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
		$search_flip = array_flip($search_arr);
		for ($i = 0; $i < $maxi; $i++) {
			$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
			if (in_array($current_str, $search_arr)) {
				$key = $search_flip[$current_str];
				$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
			}
			$strcut .= $current_str;
		}
	}
	return $strcut.$dot;
}
	
function dheader($string, $replace = true, $http_response_code = 0) {
	$string = str_replace(array("\r", "\n"), array('', ''), $string);
	if(empty($http_response_code) || phpversion() < '4.3' ) {
		@header($string, $replace);
	} else {
		@header($string, $replace, $http_response_code);
	}
	if(preg_match('/^\s*location:/is', $string)) {
		exit();
	}
}

//删除smarty_class/view_c/目录下得所有文件svn目录不删
function deleteDir($dirName){
        if(!is_dir($dirName)){
            @unlink($dirName);
            return false;
        }
        $handle = @opendir($dirName);
        while(($file = @readdir($handle)) !== false){
            if($file != '.' && $file != '..'){
                $dir = $dirName . '/' . $file;
				if($file !== '.svn'){        //svn文件略过删除
                is_dir($dir) ? $this->deleteDir($dir) : @unlink($dir);
				}
            }
        }
        closedir($handle);
       // return rmdir($dirName);
    }

function dmicrotime() {
	return array_sum(explode(' ', microtime()));
}

function setglobal($key , $value, $group = null) {
	global $_G;
	$k = explode('/', $group === null ? $key : $group.'/'.$key);
	switch (count($k)) {
		case 1: $_G[$k[0]] = $value; break;
		case 2: $_G[$k[0]][$k[1]] = $value; break;
		case 3: $_G[$k[0]][$k[1]][$k[2]] = $value; break;
		case 4: $_G[$k[0]][$k[1]][$k[2]][$k[3]] = $value; break;
		case 5: $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] =$value; break;
	}
	return true;
}

function getglobal($key, $group = null) {
	global $_G;
	$k = explode('/', $group === null ? $key : $group.'/'.$key);
	switch (count($k)) {
		case 1: return isset($_G[$k[0]]) ? $_G[$k[0]] : null; break;
		case 2: return isset($_G[$k[0]][$k[1]]) ? $_G[$k[0]][$k[1]] : null; break;
		case 3: return isset($_G[$k[0]][$k[1]][$k[2]]) ? $_G[$k[0]][$k[1]][$k[2]] : null; break;
		case 4: return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]] : null; break;
		case 5: return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] : null; break;
	}
	return null;
}

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
        case 'g': $val *= 1024;
        case 'm': $val *= 1024;
        case 'k': $val *= 1024;
    }
    return $val;
}

/*************************************************************************
page
==========================================================================
$reload :url 
$page :当前页
$tpages :总数页数
$adjacents :翻页宽度
*************************************************************************/
function page($reload, $page, $tpages, $adjacents) {
	
	$prevlabel = "&lsaquo; Prev";
	$nextlabel = "Next &rsaquo;";
	
	$out = "<div class=\"pagin\">\n";
	
	// previous
	if($page==1) {
		$out.= "<span>" . $prevlabel . "</span>\n";
	}
	elseif($page==2) {
		$out.= "<a href=\"" . $reload . "\" onfocus=\"this.blur()\" >" . $prevlabel . "</a>\n";
	}
	else {
		$out.= "<a href=\"" . $reload . "&amp;page=" . ($page-1) . "\" onfocus=\"this.blur()\" >" . $prevlabel . "</a>\n";
	}
	
	// first
	if($page>($adjacents+1)) {
		$out.= "<a href=\"" . $reload . "\" onfocus=\"this.blur()\" >1</a>\n";
	}
	
	// interval
	if($page>($adjacents+2)) {
		$out.= "...\n";
	}
	
	// pages
	$pmin = ($page>$adjacents) ? ($page-$adjacents) : 1;
	$pmax = ($page<($tpages-$adjacents)) ? ($page+$adjacents) : $tpages;
	for($i=$pmin; $i<=$pmax; $i++) {
		if($i==$page) {
			$out.= "<span class=\"current\">" . $i . "</span>\n";
		}
		elseif($i==1) {
			$out.= "<a href=\"" . $reload . "\" onfocus=\"this.blur()\" >" . $i . "</a>\n";
		}
		else {
			$out.= "<a href=\"" . $reload . "&amp;page=" . $i . "\" onfocus=\"this.blur()\" >" . $i . "</a>\n";
		}
	}
	
	// interval
	if($page<($tpages-$adjacents-1)) {
		$out.= "...\n";
	}
	
	// last
	if($page<($tpages-$adjacents)) {
		$out.= "<a href=\"" . $reload . "&amp;page=" . $tpages . "\" onfocus=\"this.blur()\" >" . $tpages . "</a>\n";
	}
	
	// next
	if($page<$tpages) {
		$out.= "<a href=\"" . $reload . "&amp;page=" . ($page+1) . "\" onfocus=\"this.blur()\" >" . $nextlabel . "</a>\n";
	}
	else {
		$out.= "<span>" . $nextlabel . "</span>\n";
	}
	
	$out.= "</div>";
	
	return $out;
}
/*page_ajax*/
function page_ajax($reload, $page, $tpages, $adjacents, $pid=0, $cid=0) {
	
	$prevlabel = "&lsaquo; Prev";
	$nextlabel = "Next &rsaquo;";
	
	$out = "<div class=\"pagin\">\n";
	
	// previous
	if($page==1) {
		$out.= "<span>" . $prevlabel . "</span>\n";
	}
	elseif($page==2) {
		$out.= "<a href=\"javascript:page_do(".$pid.','.$cid.','.'1'.");\" onfocus=\"this.blur()\" >" . $prevlabel . "</a>\n";
	}
	else {
		$out.= "<a href=\"javascript:page_do(".$pid.','.$cid.','.($page-1).");\" onfocus=\"this.blur()\" >" . $prevlabel . "</a>\n";
	}
	
	// first
	if($page>($adjacents+1)) {
		$out.= "<a href=\"javascript:page_do(".$pid.','.$cid.','.'1'.");\" onfocus=\"this.blur()\" >1</a>\n";
	}
	
	// interval
	if($page>($adjacents+2)) {
		$out.= "...\n";
	}
	
	// pages
	$pmin = ($page>$adjacents) ? ($page-$adjacents) : 1;
	$pmax = ($page<($tpages-$adjacents)) ? ($page+$adjacents) : $tpages;
	for($i=$pmin; $i<=$pmax; $i++) {
		if($i==$page) {
			$out.= "<span class=\"current\">" . $i . "</span>\n";
		}
		elseif($i==1) {
			$out.= "<a href=\"javascript:page_do(".$pid.','.$cid.','.$i.");\" onfocus=\"this.blur()\" >" . $i . "</a>\n";
		}
		else {
			
			$out.= "<a href=\"javascript:page_do(".$pid.','.$cid.','.$i.");\" onfocus=\"this.blur()\" >" . $i . "</a>\n";
			
		}
	}
	
	// interval
	if($page<($tpages-$adjacents-1)) {
		$out.= "...\n";
	}
	
	// last
	if($page<($tpages-$adjacents)) {
		$out.= "<a href=\"javascript:page_do(".$pid.','.$cid.','.$tpages.");\" onfocus=\"this.blur()\" >" . $tpages . "</a>\n";
	}
	
	// next
	if($page<$tpages) {
		$out.= "<a href=\"javascript:page_do(".$pid.','.$cid.','.($page+1).");\" onfocus=\"this.blur()\" >" . $nextlabel . "</a>\n";
	}
	else {
		$out.= "<span>" . $nextlabel . "</span>\n";
	}
	
	$out.= "</div>";
	
	return $out;
}
//page返回数据值
function page_list($page = 1,$prePageNum,$where){
	global $_G;
	$start_limit = !empty($page) ? ($page - 1) * $prePageNum : 0;
	$limit = $prePageNum ? "LIMIT $start_limit, $prePageNum" : '';
	$res = DB::query("SELECT * FROM ".$where." $limit");
	$mlogs = array();
	while($row = DB::fetch_array($res)){
		$mlogs[] = $row;
	}
	return $mlogs;
}
	
//page获取日志条数
function total_num($where){
	global $_G;	
	$res = DB::query("SELECT * FROM ".$where);
	$LogNum = DB::num_rows($res);
	return $LogNum;
}
//*********************************************************************************page_end/


function _get_client_ip() {
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$ip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$ip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}

function checkrobot($useragent = '') {
	static $kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
	static $kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';

	$useragent = empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent;

	if(!strexists($useragent, 'http://') && preg_match("/($kw_browsers)/i", $useragent)) {
		return false;
	} elseif(preg_match("/($kw_spiders)/i", $useragent)) {
		return true;
	} else {
		return false;
	}
}

//判断字符串是否存在
function strexists($string, $find) {
	return !(strpos($string, $find) === FALSE);
}

function getgpc($k, $type='GP') {
	$type = strtoupper($type);
	switch($type) {
		case 'G': $var = &$_GET; break;
		case 'P': $var = &$_POST; break;
		case 'C': $var = &$_COOKIE; break;
		default:
			if(isset($_GET[$k])) {
				$var = &$_GET;
			} else {
				$var = &$_POST;
			}
			break;
	}

	return isset($var[$k]) ? daddslashes($var[$k]) : NULL;

}

function G(){
	global $_G; 		
	$par = func_get_args();
	foreach($par as $key => $val){
		if($val != ''){$k[] =$val;}
	}
	switch(count($k)){
		case 0: $gav = $_G; break;
		case 1: $gav = $_G[$k[0]]; break;
		case 2: $gav = $_G[$k[0]][$k[1]]; break;
		case 3: $gav = $_G[$k[0]][$k[1]][$k[2]]; break;
		case 4: $gav = $_G[$k[0]][$k[1]][$k[2]][$k[3]]; break;
	}
	return $gav;
}
	
//GPC_反转义过滤(' " \ null)
function dstripslashes($string) {
	if(empty($string)) return $string;
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}
//GPC_转义过滤(' " \ null)
function daddslashes($string, $force = 1) {
	if(is_array($string)) {
		$keys = array_keys($string);
		foreach($keys as $key) {
			$val = $string[$key];
			unset($string[$key]);
			$string[addslashes($key)] = daddslashes($val, $force);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}


/**
* 自定义JS_alert
*
* @param int $msg 提示信息
* @param string $url 跳转URL
*/
function jsalert($msg,$url) {
    return "<meta http-equiv='Content-Type'' content='text/html; charset=utf-8'><script language='javascript' charset='utf-8' type='text/javascript'>alert(\"{$msg}\");location.href='{$url}';</script>";
}


//cookie处理
function dsetcookie($var, $value = '', $life = '', $prefix = 1, $httponly = false) {
	global $_G;
	$life = $life == '' ? $_G['cookie']['cookie_lifetime'] : $life;
	$_G['cookie'][$var] = $value;
	$var = ($prefix ? $_G['cookie']['cookie_pre'] : '').$var;
	$_COOKIE[$var] = $var;

	if($value == '' || $life < 0) {
		$value = '';
		$life = -1;
	}

	$life = $life > 0 ? $_G['time'] + $life : ($life < 0 ? $_G['time'] - 31536000 : 0);
	$path = $httponly && phpversion() < '5.2.0' ? $_G['cookie']['cookie_path'].'; HttpOnly' : $_G['cookie']['cookie_path'];

	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if(phpversion() < '5.2.0') {
		setcookie($var, $value, $life, $path, $_G['cookie']['cookie_domain'], $secure);
	} else {
		setcookie($var, $value, $life, $path, $_G['cookie']['cookie_domain'], $secure, $httponly);
	}
}

function getcookie($key) {
	global $_G;
	return isset($_G['cookie'][$key]) ? $_G['cookie'][$key] : '';
}


/**
* Email发送
*
* @param string $to 收件人
* @param string $title 标题
* @param string $mail_body 内容
*/
function sendmail($to,$title,$mail_body,$handle='HTML') {

include('system/class/class_email/config.email.php');
include('system/class/class_email/mail.class.php');

$smtp = new smtp($mail_server,$mail_port,true,$mail_user,$mail_pass);
$smtp->debug = true;
//附件
//$smtp->setAttachments('BDTaskReport2012-04-01.xlsx');
$smtp->sendmail($to, $mail_name,$title, $mail_body, $handle);
}
	
/**
* 字符串_解密_加密
*
* @param string $to  明文 或 密文
* @param string $operation  //1表示它表示加密
* @param string $key  密匙
* @param string $expiry  密文有效期
*/
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	$key = md5($key != '' ? $key : 'authkey');
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}

}



//返回时间
function timeop($time,$type="talk") {
    $ntime=time()-$time;
    if ($ntime<60) {
        return("刚才");
    } elseif ($ntime<3600) {
        return(intval($ntime/60)."分钟前");
    } elseif ($ntime<3600*24) {
        return(intval($ntime/3600)."小时前");
    } else {
        if ($type=="talk") {
            return(gmdate('m月d日 H:i',$time+8*3600));
        } else {
            return(gmdate('Y-m-d H:i',$time+8*3600));
        }

    }
}	 


//检查邮箱是否有效
function is_email($email) {
return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

//检查日期是否有效
function is_date($ymd, $sep='-')
{
	if(empty($ymd)) return FALSE;
	list($year, $month, $day) = explode($sep, $ymd);
	return checkdate($month, $day, $year);
}


//过滤___html
function shtmlspecialchars($string) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = shtmlspecialchars($val);
}
} else {
$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
}
return $string;
}


//数组转化字符串
function c_implode($array, $s = ',')
{
	if(empty($array)) return '';
	return is_array($array) ? implode($s, $array) : $array;
}


/**
* 转换字节数为其他单位
* @param	string	$filesize	字节大小
* @return	string	返回大小
*/
function sizecount($filesize) {
	if ($filesize >= 1073741824) {
		$filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
	} elseif ($filesize >= 1048576) {
		$filesize = round($filesize / 1048576 * 100) / 100 .' MB';
	} elseif($filesize >= 1024) {
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	} else {
		$filesize = $filesize.' Bytes';
	}
	return $filesize;
}

/**
* 除数不为0转换
*/
function zto1($v1){
	$v2 = $v1 == 0 ? 1 : 0;
	return $v2;
}
/**
* 保留2位小数
*/
function toformat($v3){
	return number_format($v3,2,'.','');
}


function is_loaded($class = '')
{
	static $_is_loaded = array();
	if ($class != '')
	{
		$_is_loaded[strtolower($class)] = $class;
	}
	return $_is_loaded;
}

function load_class($class, $directory = 'plugin')
{
	static $_classes = array();
	if (isset($_classes[$class]))
	{
		return $_classes[$class];
	}
	$name = FALSE;
	
	if(is_dir('system/'.$directory.'/'.$class)){
		if (file_exists('system/'.$directory.'/'.$class.'/'.$class.'.php')){
			$name = $class;
			if (class_exists($name) === FALSE){
				require('system/'.$directory.'/'.$class.'/'.$class.'.php');
			}
		}
	}else{
		if (file_exists('system/'.$directory.'/'.$class.'.php')){
			$name = $class;
			if (class_exists($name) === FALSE){
				require('system/'.$directory.'/'.$class.'.php');
			}
		}	
	}
	
	if ($name === FALSE)
	{
		exit('Not found class: '.$class);
	}
	is_loaded($class);
	$_classes[$class] = new $name();
	return $_classes[$class];
}
	
/*************************************************************************
Core处理
*************************************************************************/

/**
* 加载C层内部文件
*/
function LoadC($file_OR_folder='', $fun='') {
	global $_G;
	$gc = ''; $gfun='';
	$path = BASE_ROOT.'controller/';
	if(is_dir($path.$file_OR_folder)){
		if($fun != '' && strpos($fun,'-')!==false){
			list($gc,$gfun)=explode('-',$fun);
			include_once  $path.$file_OR_folder.'/C_'.$gc.'.php';
		}else{
			include_once  $path.$file_OR_folder.'/C_'.$file_OR_folder.'.php';
		}
	}else{
		include_once  $path.'C_'.$file_OR_folder.'.php';
	}
	$class = empty($gc) ? 'C_'.$file_OR_folder : 'C_'.$gc;
	$fun_v = empty($gfun) ? $fun : $gfun;
	$obj = new $class('controller');
	empty($fun) ? (method_exists($obj,'index') ? $obj->index() : '') : $obj->$fun_v();
	return $obj;
}

/** 
 * url扩展5种的url重写路由方式
 * (1)index.php?c=group&fun=topic&topicid=1 //标准默认模式
 * (2)index.php/group/topic/topicid-1   //path_info模式
 * (3)group-topic-topicid-1.html   //rewrite模式1  引用控制器内模块方法（&） <a href="{url('user','dd&v4','id=1+act=er',3)}">
 * (4)group/topic/topicid-1   //rewrite模式2       引用控制器内模块方法（-） <a href="{url('user','dd-v4','id=1+act=er',4)}">
 * (5)group/topic/topicid-1.html   //rewrite模式2  引用控制器内模块【默认类】方法（-） <a href="{url('user','v3','id=1+act=er',5)}">
 */
function url($app,$ac='',$params_str='',$urlset=4){
	global $_G;
	$str=''; $url='';
	$params_v = array();
	if($params_str != ''){
		$params_v = explode('+',$params_str);
		foreach($params_v as $k=>$v){
			list($k2,$v2) = explode('=',$v);
			$params[$k2] = $v2;
		}
	}

	switch($urlset){
		case 1:
			if(count($params_v)>0){
				foreach($params as $k=>$v){
					$str .= '&'.$k.'='.$v;
				}
			}
			if($ac==''){
				$ac = '';
			}else{
				$ac='&fun='.$ac;
			}
			$url = 'index.php?c='.$app.$ac.$str;		
		break;	
		case 2:
			if($ac == ''){
				$url = $app;
			}elseif($params_str == ''){
				$url = $app.'/'.$ac;
			}else{
				if(count($params_v)>0){
					foreach($params as $k=>$v){
						$str .= '/'.$k.'-'.$v;
					}
				}
				if($ac==''){
					$ac='';
				}else{
					$ac='/'.$ac;
				}
				$url = 'index.php/'.$app.$ac.$str;		
			}
		break;	
		case 3:
			if($ac != '' && strpos($ac,'&')!==false){
				list($gc,$gfun)=explode('&',$ac);
				$ac = $gc.'&'.$gfun;
			}
			if(count($params_v)>0){					
				foreach($params as $k=>$v){
					$str .= '-'.$k.'-'.$v;
				}
			}
			if($ac==''){
				$ac='';
			}else{
				$ac='-'.$ac;
			}
			
			$page = strpos($str,'page');
			
			if($page){
				$url = $app.$ac.$str;
			}else{
				$url = $app.$ac.$str.'.html';
			}	
		break;
		case 4:
			if($ac != '' && strpos($ac,'-')!==false){
				list($gc,$gfun)=explode('-',$ac);
				$ac = $gc.'-'.$gfun;
			}
			if($ac == ''){
				$url = $app;
			}elseif($params_str == ''){
				$url = $app.'/'.$ac;
			}else{
				if(count($params_v)>0){			
					foreach($params as $k=>$v){
						$str .= '/'.$k.'-'.$v;
					}
				}
				if($ac==''){
					$ac='';
				}else{
					$ac='/'.$ac;
				}
				$url = $app.$ac.$str;		
			}
		break;
		case 5:
			if($ac != '' && strpos($ac,'-')!==false){
				list($gc,$gfun)=explode('-',$ac);
				$ac = $gc.'-'.$gfun;
			}
			if($ac == ''){
				$url = $app;
			}elseif($params_str == ''){
				$url = $app.'/'.$ac;
			}else{
				if(count($params_v)>0){			
					foreach($params as $k=>$v){
						$str .= '/'.$k.'-'.$v;
					}
				}
				if($ac==''){
					$ac='';
				}else{
					$ac='/'.$ac;
				}
				$url = $app.$ac.$str.'.html';		
			}
		break;			
	}			
	return $_G['url'].'/'.$url;
}

/**
* URL路由解析
*/
function RouteUrl(){
	global $_G;	
	$scriptName = explode('index.php',$_SERVER['SCRIPT_NAME']);
	if(!$_G['config']['system']['rest_open']){
		$rurl = substr($_SERVER['REQUEST_URI'], strlen($scriptName[0]));
	}else{
		$rurl = @substr($_SERVER['REQUEST_URL'], strlen($scriptName[0]));
	}
	if(strpos($rurl,'?')===false){

		if(preg_match('/index.php/i',$rurl)){
			$rurl = str_replace('index.php','',$rurl);
			$rurl = substr($rurl, 1);
			$params = $rurl;
		}else{
			$params = $rurl;
		}
		
		if($rurl){
			//http://localhost/group/topic/id-1 
			if(strpos($rurl,'.html')===false){
				$params = explode('/', $params);		
				foreach( $params as $p => $v ){
					if(strpos($v,'-')!==false){
						list($gc,$gfun)=explode('-',$v);
						$v = $gc.'-'.$gfun;
					}					
					switch($p){
						case 0:$_G['gp_c']=$v;break;
						case 1:$_G['gp_fun']=$v;break;
						default:
							$kv = explode('-', $v);					
							if(count($kv)>1){
								$_GET[$kv[0]] = $kv[1];  
							}else{
								$_GET['par'.$p] = $kv[0]; 
							}
							break;
					}
				}						
			}elseif(substr_count($rurl,'/') >= substr_count($rurl,'-')){
			//http://localhost/group/topic/id-1.html	
				list($url_v,$html) = explode('.', $params);	
				$params = explode('/', $url_v);	
				foreach( $params as $p => $v ){
					if(strpos($v,'-')!==false){
						list($gc,$gfun)=explode('-',$v);
						$v = $gc.'-'.$gfun;
					}					
					switch($p){
						case 0:$_G['gp_c']=$v;break;
						case 1:$_G['gp_fun']=$v;break;
						default:
							$kv = explode('-', $v);					
							if(count($kv)>1){
								$_GET[$kv[0]] = $kv[1];  
							}else{
								$_GET['par'.$p] = $kv[0]; 
							}
							break;
					}
				}									
			}else{
			//http://localhost/group-topic-id-1.html
				$params = explode('.', $params);
				
				$params = explode('-', $params[0]);
			
				foreach( $params as $p => $v ){
					if(strpos($v,'&')!==false){
						list($gc,$gfun)=explode('&',$v);
						$v = $gc.'-'.$gfun;
					}					
					switch($p){
						case 0:$_G['gp_c']=$v;break;
						case 1:$_G['gp_fun']=$v;break;
						default:
							
							if($v) $kv[] = $v;
							
							break;
					}
				}	
				$ck = count($kv)/2;
				
				if($ck>=2){
					$arrKv = array_chunk($kv,$ck);
					foreach($arrKv as $key=>$item){
						$_GET[$item[0]] = $item[1];
					}
				}elseif($ck==1){
					$_GET[$kv[0]] = $kv[1];
				}else{
					
				}					
				
			}
		}
	}
	define('C',empty($_G['gp_c']) ? $_G['default_controller'] : $_G['gp_c']);
	define('FUN',empty($_G['gp_fun']) ? '' : $_G['gp_fun']);
	$_G['gp_c'] = C; $_G['gp_fun'] = FUN;	
	
	if($_G['config']['custom']['check_in_open']){Check_in();}	
	if($_G['config']['system']['check_roles_open']){Check_Roles();}		
	FUN == '' ? LoadC(C) : LoadC(C,FUN);	
}	

/**
 * 检查登陆用户权限
 */
function Check_Roles(){
	//if(!isset($_SESSION['user_name'])) return;
	//if($_SESSION['user_name']=='admin') return;
	if(!in_array(C.'/'.FUN,array('demo','demo/display'))){
		echo 'No access permissions page.<a href="javascript:window.history.back();">Back</a>';exit;
	}
}
